package com.jt.aop;

import com.jt.anno.Pri;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;

@Component
@Aspect
public class SpringAOP {
    //Java基础：ArrayList线程是不安全的
    private List<String> list = new Vector<>();
    @PostConstruct
    public void init(){
        list.add("add");
        list.add("update");
        list.add("delete");
        list.add("select");
    }
    /**
     * 1.获取方法中的注解@Pri(name = "add")
     * 2.获取权限的名称 name = add
     * 3.判断list结合中是否有该权限
     *      true：有权限    执行目标方法
     *      false：无权限
     * 4.规则：
     *      1.如果有多个参数，则joinpoint必须位于第一位
     *      变太写法：
     *          可以直接写注解的名称，这样可以直接为注解赋值
     * */
    @Around("@annotation(pri)") //只是拦截注解，获取注解的数据
    public Object around2(ProceedingJoinPoint joinPoint, Pri pri) throws Throwable{
        String name = pri.name();
        System.out.println("用户的权限:"+name);
        //判断list集合中是否有权限
        if(list.contains(name)){
            //true
            Object result = joinPoint.proceed();
            return result;
        }else {
            //false
            System.out.println("该用户无权限");
        }
        return null;
    }



    //@Around("execution(* com.jt.service..*.*(..))")
    public Object around1(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("环绕通知开始");
        long t1 = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long t2 = System.currentTimeMillis();
        //目标对象类型
        Class<?> target = joinPoint.getTarget().getClass();
        //目标对象类名
        String className = joinPoint.getSignature().getDeclaringTypeName();
        //目标对象方法名
        String methodName = joinPoint.getSignature().getName();
        //参数
        Object[] args = joinPoint.getArgs();
        System.out.println("耗时"+(t2-t1));
        System.out.println("类型"+target);
        System.out.println("类名"+className);
        System.out.println("方法名"+methodName);
        System.out.println("参数"+ Arrays.toString(args));
        System.out.println("返回值"+result);
        System.out.println("环绕通知结束");
        return result;
    }



}
